from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView, RetrieveUpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import UpdateAPIView

from apps.user import serializers
from apps.user.models import User
from apps.user.serializers import UserPwdSerializer

# 详情页面的显示
class UserDetailView(RetrieveUpdateAPIView):
    # queryset = User.objects.all()
    serializer_class = serializers.UserDetailSerializer


    def get_object(self):
        # 获取用户
        user = self.request.user

        # problem = models.ForeignKey(Question, on_delete=models.CASCADE,
        # related_name="replies", default=None,verbose_name="问题ID")
        #  查询所有问题ID
        replies = user.replies.all()
        user.answer_question = []
        # 遍历 问题
        for item in replies:
            # 回答的评论
            if item.type == 2:
                user.answer_question.append(item)
        return user

# 修改密码
class UserPasswordView(UpdateAPIView):
    # 使用的 序列化器
    # queryset = User.objects.filter(user=request.user)
    serializer_class = UserPwdSerializer

    def get_object(self):
        return self.request.user


# 关注与取消关注
class UserLikeView(APIView):
    # 当前用户id 关注userid
    def post(self, request, userid):
        # user当前用户对象
        user = self.request.user
        # 查询被关注的用户的信息 concern_user关注用户
        concern_user = User.objects.get(id=userid)
        # 多对多
        # fans = models.ManyToManyField(to='self', symmetrical=False, related_name='idols', null=True)  # 我的偶像有谁
        # idols 在关联查询中,代替单一对象查找多对象 ---因为是多对象 所以需要遍历
        if concern_user in user.idols.all():
            return Response({"success": False, "message": "已经关注"})
        # 数据库 添加关注的对象
        user.idols.add(concern_user)
        # 数据库 保存
        user.save()
        # 返回数据  message 字符串  success boolean
        return Response({"success": True, "message": "关注成功"})

    # 当前用户取消关注userid
    def delete(self, request, userid):
        # user当前用户对象
        user = self.request.user
        # 查询被关注的用户的信息 concern_user关注用户
        concern_user = User.objects.get(id=userid)
        # 多对多
        # fans = models.ManyToManyField(to='self', symmetrical=False, related_name='idols', null=True)
        # idols 在关联查询中,代替单一对象查找多对象 ---因为是多对象 所以需要遍历
        if concern_user not in user.idols.all():
            return Response({"success": False, "message": "已经取消关注"})
        # 数据库 删除 关注的对象
        user.idols.remove(concern_user)
        # 数据库 保存
        user.save()
        # 返回数据  message 字符串  success boolean
        return Response({"success": True, "message": "取消关注成功"})
